﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

using ERPStore.Extensions;

using CloudSoft.Extensions;

using System.Xml;

namespace ERPStore.Exporter.Providers
{
	public class KelkooExport : ExportBase
	{
		XDocument m_Document;
		string m_ShoppingInfo;

		public override void InitializeSettings(Models.Settings settings)
		{
			settings.AllowMissingDefaultImage = false;
			settings.AllowNotSellable = false;
			settings.AllowNullLongDescription = true;
			settings.AllowNullShortDescription = true;
			settings.AllowStockEmpty = false;
			settings.AllowZeroSalePrice = false;
			settings.FileName = "kelkoo.xml";
			m_ShoppingInfo = null;
		}

		public override string Name
		{
			get { return "Kelkoo"; }
		}

		public override string LeadSourceId
		{
			get { return "67171C7D-1F39-41DE-9C33-445E34B8622E"; }
		}

		public override void CreateDocument()
		{
			m_Document = new XDocument(new XDeclaration("1.0", "UTF-8", null));
			var root = new XElement("products");
			m_Document.Add(root);
		}

		public override void AddElementToDocument(ERPStore.Models.Product product, ERPStore.Models.ProductStockInfo productStock)
		{
			var description = (product.ShortDescription ?? product.LongDescription ?? product.PageTitle).Replace("|", " ").Replace("<br/>", "\r\n");
			var url = BuildEncryptedProductUrl(LeadSource, product);
			var title = product.PageTitle.Replace("|", " ");
			var offerId = product.Code;
			var price = ToCurrency(product.BestPrice.ValueWithTax,true);
			var deliveryTime = "sous 5 jours";
			var warranty = product.Warranty;
			var ecotax = (product.RecyclePrice != null) ? ToCurrency(product.RecyclePrice.ValueWithTax,true) : "";
			var unitaryPrice = string.Empty;
			if (product.SaleUnitValue > 1)
			{
				unitaryPrice = string.Format("{0} pour {1}", ToCurrency(product.BestPrice.ValueWithTax,true), product.SaleUnitValue);
			}
			var deliveryCost = (product.Shipping.Strategy == ERPStore.Models.FeeTransportStrategy.FixedPrice) ? ToCurrency(new ERPStore.Models.Price(product.Shipping.FixedPrice, product.DefaultTaxRate).ValueWithTax,true) : "0";
			var image = string.Format("http://{0}{1}", GlobalConfiguration.Configuration.Settings.DefaultUrl, string.Format(product.DefaultImage.Url, 0, 0));
			int availability = 3;
			if (productStock != null)
			{
				if (productStock.PhysicalStock > 0)
				{
					availability = 1;
				}
				else if (productStock.ProvisionnedQuantity > 0)
				{
					availability = 2;
				}
				else
				{
					availability = 6;
				}

				deliveryTime = string.Format("sous {0} jour{1}", productStock.DeliveryDaysCount, productStock.DeliveryDaysCount > 1 ? "s" : "");
			}
			var condition = "New";
			var category = GetDeepCategoryName(product);

			var item = new XElement("product"
						, new XElement("id", product.Code)
						, new XElement("model", CapitalizeWords(product.Title.Left(80)))
						, new XElement("description", new XCData(description.Left(180)))
						, new XElement("price", price)
						, new XElement("merchantcat", category)
						, new XElement("image", image)
						, new XElement("sku", product.Code)
						, new XElement("used", 0)
						, new XElement("availability", availability)
						, new XElement("deliveryprice", deliveryCost)
						, new XElement("deliverytime", deliveryTime)
						, new XElement("warranty", warranty)
						, new XElement("ecotax", ecotax)
						, new XElement("catkkid", KelkooCatMapper(product))
						);

			if (product.Brand != null)
			{
				item.Add(new XElement("brand", product.Brand.Name));
			}

			if (m_ShoppingInfo != null)
			{
				item.Add(new XElement("shoppinginfo", m_ShoppingInfo));
			}

			m_Document.Root.Add(item);
		}

		public override void SaveDocument()
		{
			var xmlWriterSettings = new XmlWriterSettings()
			{
				CheckCharacters = false,
				Indent = true,
			};
			var path = Configuration.ConfigurationSettings.AppSettings["exportPath"];
			var fileName = System.IO.Path.Combine(path, Settings.FileName);

			using (var xmlWriter = XmlWriter.Create(fileName, xmlWriterSettings))
			{
				m_Document.Save(xmlWriter);
				xmlWriter.Flush();
				xmlWriter.Close();
			}
		}

		public override void Dispose()
		{
			m_Document = null;
		}

		private string KelkooCatMapper(ERPStore.Models.Product product)
		{
			if (product.Category != null)
			{
				var rootCategory = product.Category.GetRootProductCategory();
				if (rootCategory.Code == "1500")
				{
					return "100014213"; // Outillage électro-portatif
				}
				else if (rootCategory.Code == "1000")
				{
					return "100232423"; // Outillage a main
				}
				else if (rootCategory.Code == "1100")
				{
					return "100233223"; // Quincaillerie
				}
				else if (rootCategory.Code == "1200")
				{
					return "100233223"; // Protection
				}
				else if (rootCategory.Code == "1300")
				{
					return "100233223"; // Levage
				}
				else if (rootCategory.Code == "1400")
				{
					return "100233223"; // Signaletique
				}
				else if (rootCategory.Code == "1500")
				{
					return "100233223"; // Tuyauterie
				}
				else if (rootCategory.Code == "1700")
				{
					return "108101"; // EPI
				}
				else if (rootCategory.Code == "6001")
				{
					return "100233023"; // Electricité
				}
				else if (rootCategory.Code == "6000")
				{
					return "100232523"; // Plomberie
				}
			}
			return "100233223";
		}

	}
}
